﻿using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.IO;
using System.Linq;
using System.Windows.Forms;
using System.Xml.Serialization;
using WaveletApplication.Properties;

namespace WaveletApplication
{
    public class WaveletLoader
    {
        private const string newFileName = "NewWavelet.xml";
        private readonly string _libDir;
        private Collection<WaveletSettings> _activeWaveletSettings { get; set; }   
        public WaveletLoader()
        {
            _libDir = Settings.Default.WLibraryDir;
            _activeWaveletSettings = new Collection<WaveletSettings>();
        }
        
        public void LoadWaveletSettings()
        {
                var ser = new XmlSerializer(typeof(WaveletSettings));
            if (Directory.Exists(_libDir))
            {
                var files = Directory.GetFiles(_libDir, "*.xml");
                foreach (var file in files)
                {
                    var ws = new WaveletSettings();
                    using (FileStream fs = File.OpenRead(file))
                    {
                        try
                        {
                            ws = (WaveletSettings) ser.Deserialize(fs);

                        }
                        catch (Exception e)
                        {
                            MessageBox.Show(e.Message, "Файл настройки вейвлета испорчен");
                            continue;
                        }

                    }
                    _activeWaveletSettings.Add(ws);
                }
            }
            
        }

        public void SaveWaveletSettings(WaveletSettings ws)
        {
            var s = new XmlSerializer(typeof(WaveletSettings));
            var ns = new XmlSerializerNamespaces();
            ns.Add("", "");
            //TODO: убрать скаляр
            StreamWriter writer = File.CreateText(_libDir + "\\" + newFileName);
            s.Serialize(writer, ws, ns);
            writer.Close();
        }

        public List<string> GetWaveletsNames
        {
            get
            {
                return _activeWaveletSettings.Select(x => x.WaveletName).ToList();

            }
        }

        public WaveletSettings GetWaveletByName(string name)
        {
            return _activeWaveletSettings.SingleOrDefault(x => x.WaveletName.Equals(name));
        }

        public WaveletSettings GetDefaultWavelet()
        {
            return _activeWaveletSettings.First();
        }

    }

}
